import Taro from '@tarojs/taro';
import assign from 'lodash/assign'
import omit from 'lodash/omit'
const codeMsg = {
    200: '操作成功',
    201: '操作失败',
    202: '处理中，请稍后',
    204: '操作成功，请手动刷新',
    400: '访问失败，请联系管理员-400',
    401: '没有权限',
    403: '访问受限',
    404: '页面不存在',
    405: '访问受限，请联系管理-405',
    406: '访问受限，请联系管理员-406',
    409: '访问受限，请联系管理员-409',
    410: '请求的资源被永久删除',
    415: '请求的资源类型不支持',
    422: '访问受限，请联系管理员-422',
    429: '操作过于频繁',
    500: '访问受限，请联系管理员-500',
    510: '访问受限，请联系管理员-510',
    502: '服务正在重启，请稍后再试-502',
    503: '系统维护中...',
    504: '网络信号较差，访问超时',
};
const getMsgByErrMsg = (errMsg = '',errCode) => {

    let defaultMsg = '网络开小差了，请稍后';
    let reMsg = defaultMsg;


    return reMsg;
};

function request(api, method, params, header, options = {}) {
    if (!api) {
        return new Promise((resolve) => {
            resolve();
        });
    }
    let apiUrl = api;

    let hide;
    if (false !== params.needLoading) {
        Taro.showLoading({
            title: '加载中...',
            mask: true
        });
    }


    // #ifdef MP-WEIXIN
    // let cookie = Taro.getStorageSync(globalCode.GAS_HTTPS_SESSION_KEY);
    // let token = Taro.getStorageSync(globalCode.HTTPS_TOKEN_KEY);
    // let openid = getlocatOpenid();

    // if (cookie) {
    //     header = assign({}, header, {
    //         Cookie: cookie,
    //     });
    //     if (openid) {
    //         cookie = `${cookie};WX_CURRENT_OPENID=${openid}`;
    //         header = assign({}, header, {
    //             Cookie: cookie,
    //             WXCURRENTOPENID:openid,//openid
    //         });
    //     }
    //     if (token) {
    //         cookie = `${cookie};${token}`;
    //     }
    // }

    // #endif

    //
    // header = assign({}, header, {
    //     'AUTH-TYPE': 'H5',
    // });


    // #ifdef H5||APP-PLUS

    // console.log('isHfx',getRequest('isHfx'));
    // console.log('phone',getRequest('phone'));

    // #endif

    // #ifdef APP-PLUS
    console.log('>>> request api:', apiUrl, '; method:', method, '; params:', params, '; header:', header, '; options:',
        options);
    // #endif

    return new Promise((resolve, reject) => {
        Taro.request({
            url: apiUrl,
            data: { ...omit(params, ['signal', 'needLoading', 'isCheckLogin', 'needTip'])},
            header: header,
            method: method,
            success: (res) => {
                // console.log('>> request api sp:',apiUrl,'-res:',res);
                if (false !== params.needLoading) {
                    Taro.hideLoading();
                }
                let noLogined = false;

                // #ifdef APP-PLUS
                if (-1 === api.indexOf('login') && !params.isCheckLogin) { // 如果不是 登录请求，判断是否登录过期
                    let rsp = res.data;
                    noLogined = rsp && 'undefined' !== typeof rsp.isAuthenticated && !rsp.isAuthenticated && 'Login Failure' ===
                        rsp.detailMessage;
                    if (!noLogined && rsp && 0 === rsp.status && '用户未登录' == rsp.msg) {
                        noLogined = true;
                    }
                } else {
                    // 如果是 登录请求，则直接返回 res
                    resolve(res);
                    return res;
                }
                // #endif




                if (200 != res.statusCode) {

                    if(401 == res.statusCode){
                        Taro.showModal({
                            title:'温馨提示',
                            content:'您的账号已被使用，请重新登录',
                            showCancel:false,
                            complete: (rs) => {
                                if(rs.confirm){
                                    // store.commit({
                                    //     type: 'user/unBinds'
                                    // });
                                    // store.commit({
                                    //     type: 'user/setStateByObj',
                                    //     newState: {
                                    //         notAuthor: true
                                    //     }
                                    // })
                                }
                            }
                        })
                        return false;
                    }else{
                        if(204 === res.statusCode){

                        }else{
                            Taro.showToast({
                                title: codeMsg[res.statusCode],
                                icon: 'none'
                            });
                        }

                    }

                    resolve(res);
                    return res;
                }

                // 判断是否会话过期
                if (noLogined) {

                    // store.commit({
                    //     type: 'user/unBinds'
                    // });
                    // store.commit({
                    //     type: 'user/setStateByObj',
                    //     newState: {
                    //         isExpired: true
                    //     }
                    // })

                    // #ifdef APP-PLUS
                    // 如果没有登陆，跳转到登录页
                    Taro.reLaunch({
                        url: '/pages/main/author/account'
                    });
                    // #endif

                    // #ifdef H5
                    Taro.navigateTo({
                        url: '/pages/main/author/register'
                    });
                    // #endif

                    resolve(res);
                } else {
                    resolve(res);
                }

            },
            complete: (res) => {

            },
            fail: (err) => {
                console.log('fail:',err);
                if (false !== params.needLoading) {
                    Taro.hideLoading();
                }
                // console.log('er:',err);
                let errmsg = err && err.errMsg ? err.errMsg : '';

                if (false !== params.needTip) {
                    Taro.showToast({
                        title: getMsgByErrMsg(errmsg),
                        icon: 'none'
                    });
                }

                reject(err)
            },
            ...assign({
                signal: params.signal
            }, options)
        })
    }).catch(err => {
        console.error('>>> err', err)
    });
}

function reqGet(api, params = {}, options = {}) {
    let header = {
        Accept: 'application/json;charset=UTF-8;',
    };
    if(options&&options.header){
        header = assign({}, header, {...options.header});
        delete options.header
    }
    return request(api, 'GET', params,header,options);
};

function jsonPost(api, data = {}, options = {}) {
    let header = {
        Accept: 'application/json;charset=UTF-8',
        'Content-Type': 'application/json;charset=UTF-8'
    };
    if(options&&options.header){
        header = assign({}, header, {...options.header});
        delete options.header
    }
    return request(api, 'POST', data,header, options);
};

function formPost(api, data = {}, options = {}) {
    let header = {
        'Content-Type': 'application/x-www-form-urlencoded'
    };
    if(options&&options.header){
        header = assign({}, header, {...options.header});
        delete options.header
    }
    return request(api, 'POST', data, header, options);
};


